package tcpconnect

import (
	//	"errors"
	"log"
	"msgsign"
	"net"
	"os"
	//	"runtime"
	//	"strconv"
	//	"strings"
	"message"
	"nethandle"
	"time"
	"user"
)

var lianjieshu int = 0

func StartTCPServer() {
	log.Println("启动TCP服务中。。。。。")
	go netSpeed()
	addr, err := net.ResolveTCPAddr("tcp", msgsign.TCP_PORT)
	checkErr(err)

	listen, err := net.ListenTCP("tcp", addr)
	checkErr(err)
	log.Println("Start server...")
	for {
		createConn(listen)
	}
	os.Exit(-1)
}

var NetworkSpeed int64 = 0

func netSpeed() {
	log.Println("启动流量计数。。。。。")
	timer1 := time.NewTicker(time.Minute)
	for {
		select {
		case <-timer1.C:
			NetworkSpeed = message.Network_flow / 60
			message.Network_flow = 0
		}
	}
}

func createConn(listen net.Listener) {
	conn, err := listen.Accept()
	if err == nil {
		go handle(conn)
	}
}

func checkErr(err error) {
	if err != nil {
		log.Println(err)
		os.Exit(-1)
	}
}

func errorHandle(conn net.Conn) {
	if err := recover(); err != nil {
		if conn != nil {
			nethandle.CloseConn(conn)
		}
	}
}

func handle(conn net.Conn) {
	defer errorHandle(conn)
	nethandle.NewConn()
	ui := &user.UserInfo{false, time.Now(), conn.RemoteAddr().String(), conn, "", 0}
	defer ui.Destroy()
	err := ui.HandleConn()
	if err != nil {
		log.Println(err.Error())
	}
	nethandle.CloseConn(conn)
}
